Raw Python - Filters

Filtering basically just helps filter out certain values from a list. You take a function that returns a boolean value - true or false and filters out the values that return false when you apply that function to an item and keeps those that return True.


In [1]:
x = range(10)

In [2]:
x


Out[2]:
range(0, 10)

In [3]:
def divis_by_2(num):
    return num % 2 == 0

In [4]:
divis_by_2(2)


Out[4]:
True

In [5]:
divis_by_2(3)


Out[5]:
False

In [16]:
list(map(divis_by_2, x))


Out[16]:
[True, False, True, False, True, False, True, False, True, False]

In [17]:
list(filter(divis_by_2, x))


Out[17]:
[0, 2, 4, 6, 8]

In [8]:
test_list = [
"hello",
"x,y,z. i like this.",
"this is two xx",
"this, x, here x is, here it is againx"
]

In [9]:
def has_x(my_string):
    return my_string.count("x") >= 2

In [10]:
has_x("hello")


Out[10]:
False

In [11]:
has_x("xxhello")


Out[11]:
True

In [18]:
list(filter(has_x, test_list))


Out[18]:
['this is two xx', 'this, x, here x is, here it is againx']

It acts just like map, it maps values from true to false and helps us only get those that meet the criteria


In [14]:
list(map(has_x, test_list))


Out[14]:
[False, False, True, True]

In [ ]: